<?
header( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' );
header( 'Content-type: application/javascript');

class Memcache_Mockup
{
	function get() { return false; }
	function set() { }
	function delete() {}
}

// src:
$bannerid = intval($_GET['b']);
$siteid = intval($_GET['s']);

//$memcache = new Memcache();
//$memcache->pconnect("localhost", 11211, 1);
$memcache = new Memcache_Mockup;

$db_connect = false;

// получаем инфу по баннеру
$banner = $memcache->get("remedia_banner_".$bannerid);
if(!$banner)
{
	include 'config/db.php';
	$db_connect = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
	if(!$db_connect) exit;
	if(!mysql_select_db(DB_DATABASE)) exit;
	$res = mysql_query("select * from banners where id=".$bannerid);
	if(!$res) exit;
	$banner = mysql_fetch_assoc($res);
	$memcache->set("remedia_banner_".$bannerid, serialize($banner), 0, 4000);
}
else
{	
	$banner = unserialize($banner);
}

// получаем инфу по связке сайт-баннер
$code = $memcache->get("remedia_code_".$bannerid."_".$siteid);
if(!$code)
{
	if(!$db_connect)
	{
		include 'config/db.php';
		if(!mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)) exit;
		if(!mysql_select_db(DB_DATABASE)) exit;
	}
	$res = mysql_query("select * from codes where bannerid=".$bannerid." and siteid=".$siteid);
	if(!$res) exit;
	$code = mysql_fetch_assoc($res);
	$memcache->set("remedia_code_".$bannerid."_".$siteid, serialize($code), 0, 4000);
}
else
{	
	$code = unserialize($code);
}


// учитываем проценты показов
if($code['showpercent']!='100')
{
	$prc = round( rand(0, 100000) / 1000 );
	if($prc>$code['showpercent']) exit;
}



$cache_key = 'remedia_show_'.$bannerid.'_'.$siteid;
$v = $memcache->get($cache_key);
if($v)
{
	$memcache->set($cache_key, $v+1, 0, 50000);
}
else
{
	$memcache->set($cache_key, 1, 0, 50000);
}


$click_url = 'http://'.HOST_NAME.'/click.php?s='.$siteid.'&b='.$bannerid;
$picture_url  = 'http://'.HOST_NAME.'/data/media/'.$banner['picturename'];
$flash_url  = 'http://'.HOST_NAME.'/data/media/'.$banner['flashname'];



// формируем код показа
if($banner['flashname'])
{
	// с флешом
	echo "document.write('";
	echo '<div id="banner'.$bannerid.'" style="width:'.$banner['width'].'px;"><a target="_blank" href="'.$click_url.'"><img border="0" src="'.$picture_url.'"></a></div>';
	echo "');";	
	echo "\r\n";
	echo 'swfobject.embedSWF("'.$flash_url.'?link1='.urlencode($click_url).'", "banner'.$bannerid.'", "'.$banner['width'].'", "'.$banner['height'].'", "9.0.0", "", {}, {wmode:"transparent"});';
	exit;
}
else
{
	// только картинка
	echo "document.write('";
	echo '<a target="_blank" href="'.$click_url.'"><img border="0" src="'.$picture_url.'"></a>';
	echo "');";
	exit;
}